package com.joysuch.wwyt.edu.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.zlg.common.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.entity.BpJob;
import com.joysuch.wwyt.bp.entity.contractor.BpContractor;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorStaff;
import com.joysuch.wwyt.bp.repository.BpContractorDao;
import com.joysuch.wwyt.bp.repository.BpContractorStaffDao;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpJobDao;
import com.joysuch.wwyt.core.bean.BaseAttachmentBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.JsonUtil;
import com.joysuch.wwyt.core.entity.BaseTypeGroupItem;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseAttachmentRepositoryService;
import com.joysuch.wwyt.core.service.BaseRoleDataAuthService;
import com.joysuch.wwyt.core.support.AuthorityScopeComponent;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.datasync.service.DataSyncGenerateDataService;
import com.joysuch.wwyt.edu.bean.WwytEduCertificateQueryParam;
import com.joysuch.wwyt.edu.bean.WwytEduCertificateUserVo;
import com.joysuch.wwyt.edu.entity.EduCertificateNotify;
import com.joysuch.wwyt.edu.entity.WwytEduCertificate;
import com.joysuch.wwyt.edu.entity.WwytEduCertificateUser;
import com.joysuch.wwyt.edu.enums.CertStatus;
import com.joysuch.wwyt.edu.mapper.WwytEduCertificateMapper;
import com.joysuch.wwyt.edu.mapper.WwytEduCertificateUserMapper;
import com.joysuch.wwyt.edu.service.EduCertificateNotifyService;
import com.joysuch.wwyt.edu.service.WwytEduCertificateUserService;
import com.joysuch.wwyt.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author pp
 * @since 2021-04-15
 */
@Service
public class WwytEduCertificateUserServiceImpl extends ServiceImpl<WwytEduCertificateUserMapper, WwytEduCertificateUser> implements WwytEduCertificateUserService {

    @Autowired
    private WwytEduCertificateUserMapper wwytEduCertificateUserMapper;
    @Autowired
    private BaseUserDao userDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BpJobDao jobDao;
    @Autowired
    private WwytEduCertificateMapper wwytEduCertificateMapper;
    @Autowired
    private BaseTypeGroupItemDao itemDao;
    @Autowired
    private AuthorityScopeComponent authorityScopeComponent;
    @Autowired
    private BaseAttachmentRepositoryService attachmentRepositoryService;
    @Autowired
    private BpContractorStaffDao bpContractorStaffDao;
    @Autowired
    private BpContractorDao bpContractorDao;

    @Autowired
    private DataSyncGenerateDataService dataSyncGenerateDataService;
    @Autowired
    private BaseRoleDataAuthService baseRoleDataAuthService;
    @Autowired
    private EduCertificateNotifyService eduCertificateNotifyService;


    @Override
    public void insert(WwytEduCertificateUser entity) {
        //一个证书种类的只能有一个唯一编号
        LambdaQueryWrapper<WwytEduCertificateUser> repeat = new QueryWrapper<WwytEduCertificateUser>().lambda()
                .eq(WwytEduCertificateUser::getCertId, entity.getCertId())
                .eq(WwytEduCertificateUser::getCertNo, entity.getCertNo())
                .eq(WwytEduCertificateUser::getDeleteFlag, "0");
        Integer count = wwytEduCertificateUserMapper.selectCount(repeat);
        if (count > 0) {
            throw new IllegalArgumentException("证书编号重复! 一个证书种类的只能有一个唯一编号!");
        }
        Integer aheadDays=0;
        EduCertificateNotify notify = eduCertificateNotifyService.findByCertId(entity.getCertId());
        if (notify!=null){
            aheadDays=notify.getAheadDays();
        }
        entity.setCertStatus(getEduCertStatus(entity.getTakenTime(), entity.getOutOfDateTime(), aheadDays).status.toString());
        //if (entity.getOutOfDateTime() != null) {
        //    //即将过期
        //    if ((entity.getOutOfDateTime().after(new Date())||
        //            com.joysuch.wwyt.util.DateUtils.getStartOfDay(entity.getOutOfDateTime()).equals(com.joysuch.wwyt.util.DateUtils.getStartOfDay(new Date())))
        //            && entity.getOutOfDateTime().before(DateUtils.addDays(new Date(), aheadDays))) {
        //        entity.setCertStatus(CertStatus.EXPIRING_SOON.status.toString());
        //    } else if (entity.getOutOfDateTime().after(new Date()) &&(entity.getTakenTime()==null||entity.getTakenTime().before(new Date())) ) {
        //        //有效
        //        entity.setCertStatus(CertStatus.EFFECTIVE.status.toString());
        //    }  else if (entity.getOutOfDateTime().before(new Date())) {
        //        //过期
        //        entity.setCertStatus(CertStatus.EXPIRED.status.toString());
        //    } else {
        //        entity.setCertStatus(CertStatus.NO_EFFECTIVE.status.toString());
        //    }
        //} else {
        //    entity.setCertStatus(CertStatus.NO_EFFECTIVE.status.toString());
        //}
        //默认归档
        entity.setCertificateStatus(1);
        int id = wwytEduCertificateUserMapper.insert(entity);
        //平台数据对接埋点
        dataSyncGenerateDataService.insert("wwyt_edu_certificate_user", new Long(id), "A", null);
        if (entity.getAttachmentIdJson() != null) {
            dataSyncGenerateDataService.insert("wwyt_edu_certificate_user_file", new Long(id), "A", entity.getCertId() + "_" + entity.getCertNo());
        }
    }


    /**
     * 处理证书状态
     *
     * @param startDate 有效期开始日期
     * @param endDate   有效期结束日期
     * @param remindDays 提醒天数
     * @return {@link CertStatus} 证书状态
     */
    private CertStatus getEduCertStatus(Date startDate, Date endDate, Integer remindDays) {
        // 未录入证书时间， 默认长期有效
        if (Objects.isNull(startDate) && Objects.isNull(endDate)) {
            return CertStatus.EFFECTIVE;
        }

        // 当前日期
        Date nowDate = new Date();

        // 待生效
        if (Objects.nonNull(startDate) && (startDate.after(nowDate))) {
            return CertStatus.NO_EFFECTIVE;
        }

        // 即将失效:根据提醒天数判断是否即将失效
        if (Objects.nonNull(endDate) && ((endDate.after(new Date())||
                com.joysuch.wwyt.util.DateUtils.getStartOfDay(endDate).equals(com.joysuch.wwyt.util.DateUtils.getStartOfDay(new Date())))
                && endDate.before(DateUtils.addDays(new Date(), remindDays)))) {

            return CertStatus.EXPIRING_SOON;
        }

        // 失效
        if (Objects.nonNull(endDate) && endDate.before(nowDate)) {
            return CertStatus.EXPIRED;
        }

        return CertStatus.EFFECTIVE;
    }

    @Override
    public boolean saveOrUpdate(WwytEduCertificateUser entity) {
        //平台数据对接埋点
        dataSyncGenerateDataService.insert("wwyt_edu_certificate_user", entity.getId(), "U", null);
        if (entity.getAttachmentIdJson() != null) {
            dataSyncGenerateDataService.insert("wwyt_edu_certificate_user_file", entity.getId(), "U", entity.getCertId() + "_" + entity.getCertNo());
        }

        return super.saveOrUpdate(entity);
    }

    @Override
    public WwytEduCertificateUserVo findOne(Long id) {
        WwytEduCertificateUserVo vo = new WwytEduCertificateUserVo();
        WwytEduCertificateUser wwytEduCertificateUser = wwytEduCertificateUserMapper.selectById(id);
        BeanUtils.copyProperties(wwytEduCertificateUser, vo);
        Long userId = wwytEduCertificateUser.getUserId();
        if (userId != null) {
            if (wwytEduCertificateUser.getUserContractorFlag() != null && wwytEduCertificateUser.getUserContractorFlag()) {
                Optional<BpContractorStaff> obcs = bpContractorStaffDao.findById(userId);
                if (obcs.isPresent()) {
                    BpContractorStaff staff = obcs.get();
                    vo.setUserName(staff.getName());
                    vo.setUserCode(staff.getCode());
                    if (staff.getContractorId() != null) {
                        Optional<BpContractor> obc = bpContractorDao.findById(staff.getContractorId());
                        if (obc.isPresent()) {
                            vo.setDepartName(obc.get().getCompanyName());
                        }
                    }
                }
            } else {
                Optional<BaseUser> userOptional = userDao.findById(userId);
                if (userOptional.isPresent()) {
                    BaseUser baseUser = userOptional.get();
                    vo.setUserName(baseUser.getRealName());
                    vo.setUserCode(baseUser.getCode());
                    Long departId = baseUser.getDepartId();
                    if (departId != null) {
                        Optional<BpDepart> bpDepartOptional = bpDepartDao.findById(departId);
                        if (bpDepartOptional.isPresent()) {
                            BpDepart depart = bpDepartOptional.get();
                            vo.setDepartName(depart.getName());
                        }
                    }
                    Long jobId = baseUser.getJob();
                    if (jobId != null) {
                        Optional<BpJob> jobOptional = jobDao.findById(jobId);
                        if (jobOptional.isPresent()) {
                            BpJob job = jobOptional.get();
                            vo.setJobName(job.getName());
                        }
                    }
                }
            }
        }
        Long certId = wwytEduCertificateUser.getCertId();
        if (certId != null) {
            WwytEduCertificate wwytEduCertificate = wwytEduCertificateMapper.selectById(certId);
            if (wwytEduCertificate != null) {
                vo.setCertificateName(wwytEduCertificate.getName());
                Long certTypeId = wwytEduCertificate.getCertTypeId();
                if (certTypeId != null) {
                    Optional<BaseTypeGroupItem> byId = itemDao.findById(certTypeId);
                    if (byId.isPresent()) {
                        BaseTypeGroupItem baseTypeGroupItem = byId.get();
                        vo.setCertificateTypeName(baseTypeGroupItem.getName());
                    }
                }
            }
        }
        if (StringUtil.notEmpty(wwytEduCertificateUser.getAttachmentIdJson())) {
            List<Long> attachIds = JsonUtil.fromListJson(wwytEduCertificateUser.getAttachmentIdJson(), Long.class);
            List<BaseAttachmentBean> attachmentBeans = new ArrayList<>();
            for (Long atId : attachIds) {
                BaseAttachmentBean atBean = attachmentRepositoryService.findByIdIntoBean(atId);
                attachmentBeans.add(atBean);
            }
            vo.setAttachmentBeans(attachmentBeans);
        }
        return vo;
    }


    @Override
    public ResultBean findPage(WwytEduCertificateQueryParam param) {
        //查询当前角色所能管理的部门Ids
        Set<Long> authDepartIds = baseRoleDataAuthService.findAuthDepartIdsByCurUser();
        if (CollectionUtils.isEmpty(authDepartIds)) {
            return ResultBean.defaultSuccessResult();
        }
        //证书类型条件,查出证书种类下的所有证书ids,查看证书id是否在这个集合中,取结果
        //证书类型条件查询类似于证书权限查询:查询出当前用户权限下的部门或者承包商单位的ids,找出证书的人员,查出其单位或者承包商单位的id是否在这个集合中
        Long certTypeId = param.getCertTypeId();
        List<Long> certIds = new ArrayList<>();
        Long certId = param.getCertId();
        if (certTypeId != null && certId != null) {
            //证书id查询出该证书的certTypeId,要是不同直接让查不到
            WwytEduCertificate certificate = wwytEduCertificateMapper.selectById(certId);
            Long dbCertTypeId = certificate.getCertTypeId();
            if (certTypeId.equals(dbCertTypeId)) {
                certIds.add(certId);
            } else {
                certIds.add(-2L);
            }
        } else if (certTypeId != null && certId == null) {
            LambdaQueryWrapper<WwytEduCertificate> eq = new QueryWrapper<WwytEduCertificate>().lambda()
                    .eq(WwytEduCertificate::getCertTypeId, certTypeId);
            List<WwytEduCertificate> wwytEduCertificates = wwytEduCertificateMapper.selectList(eq);
            //证书表中使用这个证书种类的证书ids
            List<Long> typeUsedIds = wwytEduCertificates.stream().map(WwytEduCertificate::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(typeUsedIds)) {
                certIds.addAll(typeUsedIds);
            } else {
                //传了certTypeId  但是没找到  就让他查不到
                certIds.add(-2L);
            }
        } else if (certTypeId == null && certId != null) {
            certIds.add(certId);
        }
        Long tenantId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        Page<WwytEduCertificateUser> wwytEduCertificateUserIPage = null;
        Page<WwytEduCertificateUser> page = new Page<>(param.getPageNum() + 1, param.getPageSize());
        //true是承包商人员
        if (param.getUserContractorFlag()) {
            //查询当前角色所能管理的承包商Ids
            Set<Long> contractorIds = bpContractorDao.findAllContractorIdsByDepartIds(authDepartIds);
            if (CollectionUtils.isEmpty(contractorIds)) {
                return ResultBean.defaultSuccessResult();
            }
            wwytEduCertificateUserIPage = wwytEduCertificateUserMapper.selectContractorCertPageByAuth(page, tenantId, orgCode, param.getNameOrCode(), contractorIds, param.getUserContractorFlag(), param.getCertNo(), certIds
                    , param.getCertificateStatus(), param.getEffectQueryStartTime(), param.getEffectQueryEndTime()
                    , param.getReviewQueryStartTime(), param.getReviewQueryEndTime(), param.getCertStatus());
        } else {
            //此时查公司人员证书
            wwytEduCertificateUserIPage = wwytEduCertificateUserMapper.selectUserCertPageByAuth(page, tenantId, orgCode, param.getNameOrCode(), authDepartIds, param.getUserContractorFlag(), param.getCertNo(), certIds
                    , param.getCertificateStatus(), param.getEffectQueryStartTime(), param.getEffectQueryEndTime()
                    , param.getReviewQueryStartTime(), param.getReviewQueryEndTime(), param.getCertStatus());
        }
        Page<WwytEduCertificateUserVo> resultPage = new Page<>();
        //包装vo
        List<WwytEduCertificateUser> records = wwytEduCertificateUserIPage.getRecords();

        List<EduCertificateNotify> notifyList = eduCertificateNotifyService.list(new LambdaQueryWrapper<EduCertificateNotify>()
                .eq(EduCertificateNotify::getStatus, 1));

        Set<Long> notifyIdSet = Sets.newHashSet();

        Map<Long, List<EduCertificateNotify>> certMap = Maps.newHashMap();
        notifyList.forEach(notify -> {
            notify.setCertIdList(new ArrayList<>());
            if (notify.getCertificates() != null && notify.getCertificates().length() > 0) {
                String[] items = notify.getCertificates().split(",");
                for (String item : items) {
                    long i = Long.parseLong(item);
                    List<EduCertificateNotify> list = certMap.get(i);
                    if (list == null) {
                        list = new ArrayList<>();
                    }
                    list.add(notify);
                    certMap.put(i, list);
                    notify.getCertIdList().add(i);
                    notifyIdSet.add(i);
                }
            }
        });

        if (!CollectionUtils.isEmpty(records)) {
            List<WwytEduCertificateUserVo> vos = records.stream().map(e -> {
                WwytEduCertificateUserVo vo = new WwytEduCertificateUserVo();
                BeanUtils.copyProperties(e, vo);

                Long userId = e.getUserId();
                if (userId != null) {
                    if (e.getUserContractorFlag() != null && e.getUserContractorFlag()) {
                        Optional<BpContractorStaff> obcs = bpContractorStaffDao.findById(userId);
                        if (obcs.isPresent()) {
                            BpContractorStaff staff = obcs.get();
                            vo.setUserName(staff.getName());
                            vo.setUserCode(staff.getCode());
                            if (staff.getContractorId() != null) {
                                Optional<BpContractor> obc = bpContractorDao.findById(staff.getContractorId());
                                if (obc.isPresent()) {
                                    vo.setDepartName(obc.get().getCompanyName());
                                }
                            }
                        }
                        vo.setPeopleType("是");
                    } else {
                        Optional<BaseUser> userOptional = userDao.findById(userId);
                        if (userOptional.isPresent()) {
                            BaseUser baseUser = userOptional.get();
                            vo.setUserName(baseUser.getRealName());
                            vo.setUserCode(baseUser.getCode());
                            Long departId = baseUser.getDepartId();
                            if (departId != null) {
                                Optional<BpDepart> bpDepartOptional = bpDepartDao.findById(departId);
                                if (bpDepartOptional.isPresent()) {
                                    BpDepart depart = bpDepartOptional.get();
                                    vo.setDepartName(depart.getName());
                                }
                            }
                            Long jobId = baseUser.getJob();
                            if (jobId != null) {
                                Optional<BpJob> jobOptional = jobDao.findById(jobId);
                                if (jobOptional.isPresent()) {
                                    BpJob job = jobOptional.get();
                                    vo.setJobName(job.getName());
                                }
                            }
                        }
                        vo.setPeopleType("否");
                    }
                }
                Long firstCertId = e.getCertId();
                if (firstCertId != null) {
                    WwytEduCertificate wwytEduCertificate = wwytEduCertificateMapper.selectById(firstCertId);
                    if (wwytEduCertificate != null) {
                        List<EduCertificateNotify> certificateNotifies = certMap.get(firstCertId);
                        int lineColor = 0;
                        if (vo.getOutOfDateTime() != null && System.currentTimeMillis() > DateUtil.endOfDay(vo.getOutOfDateTime()).getTime()) {
                            lineColor = 2;
                        }
                        if (certificateNotifies != null) {
                            for (EduCertificateNotify c : certificateNotifies) {
                                Integer aheadDays = c.getAheadDays();
                                if (aheadDays == null) {
                                    continue;
                                }
                                if (c.getStatus() != null && c.getStatus() == 1) {
                                    if (c.getType() == null) {
                                        continue;
                                    }
                                    // 0 到期提醒
                                    if (0 == c.getType().intValue()) {
                                        int color = 0;
                                        if (vo.getOutOfDateTime() != null) {
                                            long l = vo.getOutOfDateTime().getTime() - aheadDays * 24 * 3600 * 1000;
                                            long now = System.currentTimeMillis();
                                            if (vo.getOutOfDateTime().getTime() < now) {
                                                color = 2;
                                            } else if (now > l) {
                                                color = 1;
                                            }
                                        }
                                        if (color >= lineColor) {
                                            lineColor = color;
                                        }
                                    }
                                    // 复证提醒
                                    else if (1 == c.getType().intValue()) {
                                        int color = 0;
                                        if (vo.getRepeatViewDateTime() != null) {
                                            long l = vo.getRepeatViewDateTime().getTime() - aheadDays * 24 * 3600 * 1000;
                                            long now = System.currentTimeMillis();
                                            if (vo.getRepeatViewDateTime().getTime() < now) {
                                                color = 2;
                                            } else if (now > l) {
                                                color = 1;
                                            }
                                        }
                                        if (color >= lineColor) {
                                            lineColor = color;
                                        }
                                    }
                                }
                            }
                        }

                        vo.setLineColor(lineColor);

                        vo.setCertificateName(wwytEduCertificate.getName());
                        Long firstCertTypeId = wwytEduCertificate.getCertTypeId();
                        if (firstCertTypeId != null) {
                            Optional<BaseTypeGroupItem> byId = itemDao.findById(firstCertTypeId);
                            if (byId.isPresent()) {
                                BaseTypeGroupItem baseTypeGroupItem = byId.get();
                                vo.setCertificateTypeName(baseTypeGroupItem.getName());
                            }
                        }
                    }
                }
                return vo;
            }).collect(Collectors.toList());
            resultPage.setRecords(vos);
            resultPage.setTotal(wwytEduCertificateUserIPage.getTotal());
            return ResultBean.pageData(resultPage.getRecords(), resultPage.getTotal());
        }
        return ResultBean.pageData(resultPage.getRecords(), resultPage.getTotal());
    }

    @Override
    public WwytEduCertificateUser checkNeedUpdate(Long userId, Boolean userContractorFlag, Long certificateId, String certNo) {
        LambdaQueryWrapper<WwytEduCertificateUser> eq = new QueryWrapper<WwytEduCertificateUser>().lambda()
                .eq(WwytEduCertificateUser::getUserId, userId)
                .eq(WwytEduCertificateUser::getUserContractorFlag, userContractorFlag)
                .eq(WwytEduCertificateUser::getCertId, certificateId)
                .eq(WwytEduCertificateUser::getCertNo, certNo)
                .eq(WwytEduCertificateUser::getTenentId, Context.getCurrentTenantId())
                .eq(WwytEduCertificateUser::getOrgCode, Context.getCompanyCode());
        WwytEduCertificateUser wwytEduCertificateUser = wwytEduCertificateUserMapper.selectOne(eq);
        return wwytEduCertificateUser;
    }

    @Override
    public List<WwytEduCertificateUser> selectByCertIds(List<Long> idList) {
        LambdaQueryWrapper<WwytEduCertificateUser> eq = new QueryWrapper<WwytEduCertificateUser>().lambda()
                .in(WwytEduCertificateUser::getCertId, idList)
                .eq(WwytEduCertificateUser::getDeleteFlag, "0")
                .eq(WwytEduCertificateUser::getTenentId, Context.getCurrentTenantId())
                .likeRight(WwytEduCertificateUser::getOrgCode, Context.getCompanyCode());
        List<WwytEduCertificateUser> certificateUsers = wwytEduCertificateUserMapper.selectList(eq);
        return certificateUsers;
    }

    @Override
    public List<WwytEduCertificateUser> findCertificates(Date date, String certStatus) {
        List<WwytEduCertificateUser> list = wwytEduCertificateUserMapper.findCertificates(date, certStatus);
        return list;
    }

    @Override
    public List<WwytEduCertificateUser> findFutureCertificates(Date date, String certStatus) {
        List<WwytEduCertificateUser> list = wwytEduCertificateUserMapper.findFutureCertificates(date, certStatus);
        return list;
    }

    private LambdaQueryWrapper<WwytEduCertificateUser> buildWrapper(WwytEduCertificateQueryParam param) {
        //人员条件
        String nameOrCode = param.getNameOrCode();
        List<Long> userIds = new ArrayList<>();
        if (StringUtil.notEmpty(nameOrCode)) {
            //删除的人员 持证也能查到
            if (param.getUserContractorFlag() != null && param.getUserContractorFlag()) {
                userIds = bpContractorStaffDao.findIdsByNameOrCode(nameOrCode);
            } else if (param.getUserContractorFlag() != null && !param.getUserContractorFlag()) {
                userIds = userDao.findIdsByRealNameContainingOrCodeContaining(nameOrCode);
            }
            if (CollectionUtils.isEmpty(userIds)) {
                return null;
            }
        }

        //证书类型条件
        Long certTypeId = param.getCertTypeId();
        List<Long> certIds = new ArrayList<>();
        Long certId = param.getCertId();
        if (certTypeId != null && certId != null) {
            //证书id查询出该证书的certTypeId,要是不同直接让查不到
            WwytEduCertificate certificate = wwytEduCertificateMapper.selectById(certId);
            Long dbCertTypeId = certificate.getCertTypeId();
            if (certTypeId.equals(dbCertTypeId)) {
                certIds.add(certId);
            } else {
                certIds.add(-2L);
            }
        } else if (certTypeId != null && certId == null) {
            LambdaQueryWrapper<WwytEduCertificate> eq = new QueryWrapper<WwytEduCertificate>().lambda()
                    .eq(WwytEduCertificate::getCertTypeId, certTypeId);
            List<WwytEduCertificate> wwytEduCertificates = wwytEduCertificateMapper.selectList(eq);
            //证书表中使用这个证书种类的证书ids
            List<Long> typeUsedIds = wwytEduCertificates.stream().map(WwytEduCertificate::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(typeUsedIds)) {
                certIds.addAll(typeUsedIds);
            } else {
                //传了certTypeId  但是没找到  就让他查不到
                certIds.add(-2L);
            }
        } else if (certTypeId == null && certId != null) {
            certIds.add(certId);
        }
        ArrayList<Long> objects = new ArrayList<>();
        objects.add(-2L);
        boolean isSuperAdmin = Context.getCurrentUser().isSuperAdmin();
        LambdaQueryWrapper<WwytEduCertificateUser> wrapper = new QueryWrapper<WwytEduCertificateUser>().lambda()
                .eq(WwytEduCertificateUser::getTenentId, Context.getCurrentTenantId())
                .likeRight(WwytEduCertificateUser::getOrgCode, Context.getCompanyCode())
                .in(!isSuperAdmin && CollectionUtils.isEmpty(authorityScopeComponent.authorityUserIdData()), WwytEduCertificateUser::getUserId, objects)
                .in(!CollectionUtils.isEmpty(userIds), WwytEduCertificateUser::getUserId, userIds)
                .in(!CollectionUtils.isEmpty(certIds), WwytEduCertificateUser::getCertId, certIds)
                //有效范围
                .between(param.getEffectQueryStartTime() != null && param.getEffectQueryEndTime() != null
                        , WwytEduCertificateUser::getOutOfDateTime, param.getEffectQueryStartTime(), param.getEffectQueryEndTime())
                //复证
                .between(param.getReviewQueryEndTime() != null && param.getReviewQueryStartTime() != null
                        , WwytEduCertificateUser::getRepeatViewDateTime, param.getReviewQueryStartTime(), param.getReviewQueryEndTime())
                //持证状态
                .eq(param.getCertificateStatus() != null, WwytEduCertificateUser::getCertificateStatus, param.getCertificateStatus())
                .eq(WwytEduCertificateUser::getDeleteFlag, '0')
                .likeRight(StringUtils.isNotBlank(param.getCertNo()), WwytEduCertificateUser::getCertNo, param.getCertNo())
                .orderBy(true, false, WwytEduCertificateUser::getUpdateTime);

        return wrapper;
    }
}
